//
//  WBMainViewController.swift
//  微博
//
//  Created by 于子浩 on 2017/5/20.
//  Copyright © 2017年 于子浩. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

       setupChildControllers()
       setupComposeBUttton()
       
    }

   lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    //按钮点击方法
    func composeStatus() {
        
        print("点击加号")
    }
    
}

//extension 类似于oc的分类，在swift中还可以用来切分代码块
//可以吧功能相近的函数，放在一个extension中
//便于代码维护
//注意：和oc的分类一样，extension 中不能定义属性
//MARK: - 设置界面
private extension WBMainViewController{
    
    //设置加号按钮
    func setupComposeBUttton(){
    
        tabBar.addSubview(composeButton)
        
        //计算按钮宽度
        let count = CGFloat (childViewControllers.count)
        let width = tabBar.bounds.width / count
        
        //CGRectInset 整数向内缩进，负数向外
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0)
        composeButton.addTarget(self, action:#selector(composeStatus), for: .touchUpInside)
        
    }
    
    //设置所有子控制器
     func setupChildControllers(){
    
        let array = [
        
            ["clsName" : "WBHomeViewController","title":"首页","imageName":"home"],
            ["clsName" : "WBMessageViewController","title":"消息","imageName":"message_center"],
            ["clsName" : "UIViewController"],
            ["clsName" : "WBDiscoverViewController","title":"发现","imageName":"discover"],
            ["clsName" : "WBProfileViewController","title":"我","imageName":"profile"]
        ]
        
        var arrayM = [UIViewController]()
        
        for dict in array {
            
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    
    //使用字典创建一个子控制器
     func controller(dict:[String : String]) -> UIViewController{
    
        guard let clsName = dict["clsName"],
              let title = dict["title"],
              let imageName = dict["imageName"],
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else {
             
              return UIViewController()
        }

     //创建视图控制器
        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //设置tabbar标题字体大小、颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        
        //实例化导航控制器的时候会调用push方法，将rootVC压入栈底
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
    
    
}
